package com.flute.framework.search.sort;

import com.flute.framework.spliter.WordSpliter;
import com.flute.tools.util.StringUtil;
import com.flute.tools.util.WordUtil;

public class ScoreUtil {

	public static float getWordDefaultScore(String string, String keyword) {
		return getLengthScore(string, keyword)
				+ getPositionScore(string, keyword);
	}

	/**
	 * 值范围0-1
	 * 
	 * @param string
	 * @param keyword
	 * @return
	 */
	public static float getLengthScore(String string, String keyword) {
		string = StringUtil.getStandardString(string);
		keyword = StringUtil.getStandardString(keyword);
		float score = 0f;
		if (string.contains(keyword)) {
			score = Float.valueOf(score + keyword.length())
					/ Float.valueOf(string.length());
		} else if (isRelative(string, keyword)) {
			score = score + Float.valueOf(keyword.length())
					/ Float.valueOf(string.length());
		}

		return score;
	}

	/**
	 * 值范围 0-110
	 * 
	 * @param string
	 * @param keyword
	 * @return
	 */
	public static float getPositionScore(String string, String keyword) {
		string = StringUtil.getStandardString(string);
		keyword = StringUtil.getStandardString(keyword);
		float score = 0f;
		int po = string.indexOf(keyword);
		// 关键字所在的位置信息
		if (po > -1) {
			score = 100 * Float.valueOf(keyword.length())
					/ Float.valueOf(keyword.length() + po);
		}

		// 关键字间距
		String[] ks = WordSpliter.getInstance().split(keyword);
		if (ks != null) {
			for (String k : ks) {
				if (!string.contains(k)) {
					return score;
				}
			}
			int length = 0;
			for (int i = 0; i < ks.length - 1; i++) {
				length = WordUtil.getPositionDistance(ks[i], ks[i + 1], string);
			}
			score = score + 10 * Float.valueOf(string.length() - length)
					/ Float.valueOf(string.length());
		}
		
		return score;
	}

	private static boolean isRelative(String string, String keyword) {
		String[] ks = WordSpliter.getInstance().split(keyword);
		for (String k : ks) {
			if (!string.contains(k)) {
				return false;
			}
		}

		return true;
	}

}
